<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" :rows="2" :collapse="true" labelWidth="100" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <FilterTable
      ref="taskEntryTable"
      height="auto"
      columnsRef="tasksEntryTable"
      :columns="tableColumns"
      :datakey="'rows'"
      :fetchapi="fetchApi"
      :params="fetchParams"
      selectionType="single"
      :onColumnsChange="columns => (this.tableColumns = columns)"
      :onRowSelectChange="RowSelectData"
    >
      <template slot="controls">
        <!-- columns => this.selectColumns = columns -->
        <el-button size="small" type="primary" @click="inputClick">{{ isTRACE_TAG == 80581003 || isTRACE_TAG == 80581004 ? '问卷详细' : '问卷录入' }}</el-button>
        <el-button size="small" type="primary" @click="repairHistory">维修历史</el-button>
        <el-button size="small" type="primary" @click="returnHistory">回访历史</el-button>
        <el-button size="small" type="primary">导出</el-button>
      </template>
    </FilterTable>

    <!-- 问卷录入 destroyOnClose-->
    <Drawer :visible.sync="questionnaire" title="流失报警回访信息录入" destroyOnClose width="1300" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <RemindInputs :remindData="selectData" :buttonType="type" @close="closeQuestionNaire"></RemindInputs>
    </Drawer>

    <!-- 维修历史 -->
    <BaseDialog :visible.sync="history" title="维修历史" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <RepairHistory :getdata="selectColumns[0]" @close="closeRequireHistory"></RepairHistory>
    </BaseDialog>

    <!-- 回访历史 -->
    <Drawer :visible.sync="returnHis" title="回访信息" destroyOnClose width="1300" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ReturnHisModel :getdata="selectColumns" @close="closeReturnHis"></ReturnHisModel>
    </Drawer>
  </div>
</template>
<!--
todo:
增加查询条件“流失提醒类别：预警，流失，摇摆；”
逻辑校验：
以最近进站日期为准，距离当前日期间隔时间为预警天数；
如预警天数介于流失限制与最大限制之间的，意味即将流失客户（流失：当前时间-上次回厂时间>预警日期)；
介于最大限制与最小限制之间的为摇摆客户（摇摆：最大限制<当前时间-上次回厂时间<最小限制之间）；
未流失:当前时间-上次回厂时间<最小限制
-->
<script>
import { jsonToHump } from '@/utils/index';
import RemindInputs from '@/pages/customerRepair/customerCare/maintenanceRemind/remindInputs.vue'; // 问卷录入
import ReturnHisModel from './returnHisModel'; // 回访历史
import RepairHistory from '@/pages/repair/business/customer/Repairhistory/historypop.vue'; // 维修历史
import { queryLossReturnVisit } from '@/api/customerRepair/customerLoss/taskEntry';
import { getBrandSelect, getSeriesSelect, getModelSelect } from '@/api/customerRepair/customerLoss/resultQuery';
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import {
  getBrand,
  getSeries,
  getModel,
  getRegion,
  getExcelList,
  remindAssign,
  getMaintainAdvisor,
  getDcrcAdvisor,
  getInsuranceAdvisor
} from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import { dictionary } from '@/utils/dictMixin';
export default {
  name: 'taskEntry',
  components: {
    RemindInputs,
    ReturnHisModel,
    RepairHistory
  },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createtopFilterList(),
      fetchParams: { xhrAbort: false },
      fetchApi: queryLossReturnVisit,
      selectColumns: [],
      isTRACE_TAG: null,
      tableColumns: this.createTableColumns(),
      questionnaire: false,
      history: false,
      returnHis: false,
      type: null,
      selectData: null
    };
  },
  mounted() {
    // 初始化品牌下拉框
    this.initBrandSelect();
    this.queryBrand();
    this.querySeries();
    this.queryModel();
    this.getEmp();
  },

  methods: {
    // 初始化 品牌
    async initBrandSelect() {
      const res = await getBrandSelect();
      this.topFilterList.find(item => item.fieldName === 'brand').itemList = res.data.map(x => ({ value: x.brandId + '', text: x.brandName }));
    },
    changeBrandSelect(val) {
      // 清空车系 车型
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'series'));
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'model'));
      if (!val) return;
      this.getSeriesSelect(val);
    },
    changeSeriesSelect(val) {
      // 清空车型
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'model'));
      if (!val) return;
      this.getModelSelect(val);
    },
    // 初始化车系
    async getSeriesSelect(brandCode) {
      const res = await getSeriesSelect(brandCode);
      this.topFilterList.find(item => item.fieldName === 'series').itemList = res.data.map(x => ({ value: x.seriesId + '', text: x.seriesName }));
    },
    // 初始化车型
    async getModelSelect(seriesCode) {
      // 获取品牌代码
      const brandCode = this.topFilterList.find(item => item.fieldName === 'brand').initialValue;
      const res = await getModelSelect(brandCode, seriesCode);
      this.topFilterList.find(item => item.fieldName === 'model').itemList = res.data.map(x => ({ value: x.modelId + '', text: x.modelName }));
    },
    // 获取全部员工
    async getEmp() {
      const res = await getDealerUser();
      this.topFilterList.find(item => item.fieldName === 'trancer').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    // 查询所有品牌(供table使用)
    async queryBrand() {
      const res = await getBrand();
      this.tableColumns.find(x => x.dataIndex === 'brand_name').editItems = res.data.map(x => ({ text: x.BRAND_NAME, value: x.BRAND_ID + '' }));
    },
    // 查询所有车系(供table使用)
    async querySeries() {
      const res = await getSeries();
      this.tableColumns.find(x => x.dataIndex === 'series_name').editItems = res.data.map(x => ({ text: x.SERIES_NAME, value: x.SERIES_ID + '' }));
    },
    // 查询所有车型(供table使用)
    async queryModel() {
      const res = await getModel();
      this.tableColumns.find(x => x.dataIndex === 'model').editItems = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_ID + '' }));
    },
    createtopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '车主编号',
          fieldName: 'ownerNo'
        },
        {
          type: 'INPUT',
          label: '车主名称',
          fieldName: 'ownerName'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          itemList: [],
          change: val => {
            this.changeBrandSelect(val);
          },
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          itemList: [],
          change: val => {
            this.changeSeriesSelect(val);
          },
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          itemList: [],
          placeholder: '请选择'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        },
        {
          type: 'SELECT',
          label: '跟踪状态',
          fieldName: 'traceStatus',
          itemList: this.createDictList('8058'),
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '跟踪员',
          fieldName: 'trancer',
          filterable: true,
          itemList: [],
          placeholder: '请选择'
        }
      ];
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主编号',
          dataIndex: 'OWNER_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主名称',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主性别',
          dataIndex: 'GENDER',
          sorter: true,
          render: props => {
            return <span>{props.row.GENDER ? this.createDictText(props.row.GENDER, '8012') : ''}</span>;
          }
        },
        {
          title: '联系人',
          dataIndex: 'CONTACTOR_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人电话',
          dataIndex: 'CONTACTOR_PHONE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '联系人手机',
          dataIndex: 'CONTACTOR_MOBILE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: '200'
        },
        {
          title: '品牌',
          dataIndex: 'brand_name',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '车系',
          dataIndex: 'series_name',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '车型',
          dataIndex: 'model',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '车主电话',
          dataIndex: 'PHONE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主手机',
          dataIndex: 'MOBILE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'E_MAIL',
          dataIndex: 'E_MAIL',
          sorter: true,
          filter: true,
          hidden: true,
          filterType: 'input'
        },
        {
          title: '联系人地址',
          dataIndex: 'CONTACTOR_ADDRESS',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车主地址',
          dataIndex: 'ADDRESS',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '跟踪员',
          dataIndex: 'EMPLOYEE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结束跟踪',
          dataIndex: 'TRACE_TAG',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.TRACE_TAG, '1004')}</div>;
          }
        },
        {
          title: '跟踪状态',
          dataIndex: 'TRACE_STATUS',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.createDictText(props.row.TRACE_STATUS, '8058')}</span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '上次录入时间',
          dataIndex: 'INPUT_DATE',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '销售日期',
          dataIndex: 'SALES_DATE',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        }
        // {
        //   title: '是否回厂',
        //   dataIndex: 'IS_RETURN_FACTORY',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // }
      ];
    },
    // 选中的数据
    RowSelectData(val) {
      this.selectColumns = val;
      if (val.length !== 0) {
        this.isTRACE_TAG = this.selectColumns[0].TRACE_STATUS;
      }
    },
    // 搜索
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },

    collapseHandle() {
      this.$nextTick(() => {});
    },

    getData() {},

    // 问卷录入
    inputClick() {
      if (this.selectColumns.length) {
        this.selectData = _.cloneDeep(this.selectColumns[0]);
        jsonToHump(this.selectData);
        this.type = 1;
        this.questionnaire = true;
      } else {
        this.$message.warning('请选择表格数据');
      }
    },
    closeQuestionNaire(val) {
      this.questionnaire = val;
    },

    // 维修历史
    repairHistory() {
      if (this.selectColumns.length) {
        this.history = true;
      } else {
        this.$message.warning('请选择表格数据');
      }
    },
    closeRequireHistory() {
      this.history = false;
    },

    // 回访历史
    returnHistory() {
      if (this.selectColumns.length) {
        this.returnHis = true;
      } else {
        this.$message.warning('请选择表格数据');
      }
    },
    closeReturnHis(val) {
      this.returnHis = val;
    }
  }
};
</script>

<style scoped lang="less"></style>
